package basetest;

import org.junit.Test;
import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;

import static java.lang.System.currentTimeMillis;

/**
 * @author DuJiabao
 * @create 2021-01-15 21:18
 * 批量插入数据
 */
public class BatchInsertTest {
    @Test
    public void test() {
        Connection connection = null;
        PreparedStatement ps = null;
        String sql = "insert into user_info(id) values(?)";  // 一定要用values！
        long startTime = currentTimeMillis();
        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            connection.setAutoCommit(false); // 关闭自动提交，等所有batch execute完再提交
            for(int i = 1;i <= 1000000;i++){
                ps.setObject(1, i);
                //1."攒"sql
                ps.addBatch();
                if(i % 500 == 0){
                    //2.执行batch
                    ps.executeBatch();
                    //3.清空batch
                    ps.clearBatch();
                }
            }
            connection.commit();  // 提交
            long endTime = currentTimeMillis();
            System.out.println(endTime - startTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeSource(connection);
            JDBCUtils.closeSource(ps);
        }
    }
}
